<script setup>
import { ref, getCurrentInstance, onMounted, computed, reactive } from 'vue'
import protobufjson from '@renderer/common/protobuf.json'
import * as protobuf from 'protobufjs'
import * as pako from 'pako'
import { ElMessage, ElMessageBox, dayjs, ElNotification } from 'element-plus'
import { Eleme } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'

import utc from 'dayjs/plugin/utc'
import duration from 'dayjs/plugin/duration'
dayjs.extend(utc)
dayjs.extend(duration)
const route = useRoute()
const router = useRouter()

const internalInstance = getCurrentInstance()
let electron = null
if (window.electron) {
  electron = window.electron
}

let columns = ref([])
let tableData = ref([])
let total = ref(0)
let pageIndex = ref(1)
let pageSize = ref(100)
let loading = ref(false)
// 批量创建WebSocket
let map_wss = ref([])

// 每几个账号使用一个IP
let AccountIpNumber = ref(3)
// wss连接数
let wss_connect = ref(0)
// 直播间人数
let onlineUserForAnchor = ref('')
// 上线类型
let OnlineType = ref(1)
// 任务信息对象
let TaskObjInfo = ref({ number: 0 })

let WebSocketStr = ref('ws://127.0.0.1:9898')
// let ws_task = new WebSocket('wss://hn-cloud.youdream.wang/wss/')
let ws_task = null

// 表单查询
let formInline = reactive({
  task_name: '',
  createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
})

columns.value.push(
  ...[
    {
      align: 'center',
      width: '50',
      show: true,
      fixed: false,
      prop: 'id',
      label: '序号'
    },
    {
      align: 'center',
      width: '150',
      show: true,
      fixed: false,
      prop: 'task_name',
      label: '任务的标题'
    },
    {
      align: 'center',
      width: '220',
      show: true,
      fixed: false,
      prop: 'live_url',
      label: '主播的直播间链接地址'
    },
    {
      align: 'center',
      width: '100',
      show: true,
      fixed: false,
      prop: 'duration',
      label: '时长'
    },
    {
      align: 'center',
      width: '150',
      show: true,
      fixed: false,
      prop: 'number',
      label: '人数'
    },
    {
      align: 'center',
      width: '150',
      show: true,
      fixed: false,
      prop: 'room_id',
      label: '直播间Id'
    },
    {
      align: 'center',
      width: '150',
      show: true,
      fixed: false,
      prop: 'task_status',
      label: '任务状态'
    },
    {
      align: 'center',
      width: '150',
      show: true,
      fixed: false,
      prop: 'sec_user_id',
      label: '主播的加密ID'
    },
    {
      align: 'center',
      width: '150',
      show: true,
      fixed: false,
      prop: 'nickname',
      label: '主播的昵称'
    },
    {
      align: 'center',
      width: '150',
      show: true,
      fixed: false,
      prop: 'live_name',
      label: '直播间名称'
    },
    {
      align: 'center',
      width: '150',
      show: true,
      fixed: false,
      prop: 'user_id',
      label: '主播的ID'
    },
    {
      align: 'center',
      width: '200',
      show: true,
      fixed: false,
      prop: 'home',
      label: '主播的个人主页地址'
    },
    {
      align: 'center',
      width: '150',
      show: true,
      fixed: 'right',
      prop: 'start_time',
      label: '任务开始时间'
    },
    {
      align: 'center',
      width: '150',
      show: true,
      fixed: 'right',
      prop: 'end_time',
      label: '任务结束时间'
    },
    // {
    //   align: 'center',
    //   width: '100',
    //   show: true,
    //   fixed: 'right',
    //   prop: 'createdAt',
    //   label: '创建时间'
    // },
    // {
    //   align: 'center',
    //   width: '100',
    //   show: true,
    //   fixed: 'right',
    //   prop: 'updatedAt',
    //   label: '更新时间'
    // },
    {
      align: 'center',
      width: '300',
      show: true,
      fixed: 'right',
      prop: 'operation',
      label: '操作'
    }
  ]
)
/**
 *
 * @returns 任务计时
 *
 */

let suspend = ref(false)
let finish = ref(false)
let clock = ref(null)
let beginTask = ref('')

// let countObj = ref({
//   endTime: '',
//   showTime: '00:00:00'
// })

let endTime = ref('00:00:00')
let showTime = ref('00:00:00')

let payTimer = ref(null)

async function TaskReckonTime() {
  try {
    if (clock.value) {
      return
    }
    // endTime.value = dayjs().add(TaskObjInfo.value.duration, 'h').format('YYYY-MM-DD HH:mm:ss')
    endTime.value = dayjs(TaskObjInfo.value.end_time).format('YYYY-MM-DD HH:mm:ss')
    clock.value = setInterval(() => {
      beginTask.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
      TaskObjInfo.value.beginTask = beginTask.value
      localStorage.setItem(TaskObjInfo.value.id + '', JSON.stringify(TaskObjInfo.value))
      let times = (new Date(endTime.value) - new Date(dayjs().format('YYYY-MM-DD HH:mm:ss'))) / 1000
      let hours = parseInt((times / 60 / 60) % 24) //计算小时
      hours = hours < 10 ? '0' + hours : hours
      let minutes = parseInt((times / 60) % 60) //计算分钟
      minutes = minutes < 10 ? '0' + minutes : minutes
      let seconds = parseInt(times % 60) //计算秒数
      seconds = seconds < 10 ? '0' + seconds : seconds
      if (hours <= 0 && minutes <= 0 && seconds <= 0) {
        showTime.value = '任务结束'
        EndTask()
        clearInterval(payTimer.value)
      } else {
        showTime.value = `${hours}:${minutes}:${seconds}`
      }
    }, 1000)
  } catch (error) {
    ElMessage({
      type: 'error',
      message: JSON.stringify(error.message)
    })
  }
}

/**
 *
 * 发送接收任务的websocket
 *
 */

function ws_taskOpen() {
  if (ws_task) {
    ElMessage({
      type: 'warning',
      message: 'websocket处于连接中!'
    })
    return
  }
  ws_task = new WebSocket(WebSocketStr.value)
  ws_task.onopen = (open) => {
    console.warn('ws_task-open:', '')
    ElMessage({
      type: 'success',
      message: '连接成功!'
    })
  }
  ws_task.onmessage = (msg) => {
    console.warn('ws_task-msg:', msg.data)
    try {
      let obj = JSON.parse(msg.data)
      if ((obj.cmd = 'sen_wss_num')) {
        wss_connect.value = obj.wss_connect
        // map_wss.value = obj.wss_num
        onlineUserForAnchor.value = obj.onlineUserForAnchor + ''
      }
    } catch (error) {}
  }
  ws_task.addEventListener('sen_wss_num', (data) => {
    console.warn(data)
  })
  ws_task.onclose = (close) => {
    console.warn('ws_task-close:', close)
    ws_task = null
    ElMessage({
      type: 'error',
      message: '连接关闭!'
    })
  }
  ws_task.onerror = (error) => {
    console.warn('ws_task-error:', error)
    ws_task = null
  }
}

function ws_taskClose() {
  if (ws_task) {
    ws_task.close()
    return
  }
  ElMessage({
    type: 'error',
    message: '连接已经关闭!'
  })
}

// cmd CreateTask DeleteTask  GetTask FinishTask
function sendTo(message) {
  if (ws_task) {
    ws_task.send(JSON.stringify(message))
    return
  }
  ElMessage({
    type: 'error',
    message: 'websocket服务连接关闭!'
  })
}

/**
 *
 * @returns 获取代理IP列表
 *
 */

let proxyipLst = ref([])
let ProxyIpLType = ref(0)
let ProxyIpNumber = ref(1)
let ProxyAuth = ref('dou318:dou318')
async function getProxyIpList() {
  let localIp = localStorage.getItem('proxyipLst')
  let proxyapi = getdps(ProxyIpLType.value, ProxyIpNumber.value)
  const response_ = await fetch(proxyapi, {
    method: 'GET',
    body: undefined
  })
  let response = await response_.text()
  if (response.includes('ERROR')) {
    ElMessage({
      type: 'error',
      message: response
    })
    return
  }
  ElMessage({
    type: 'success',
    message: '更新成功!'
  })
  if (response) {
    let text = response.split('\r\n')
    let obj = []
    for (const iterator of text) {
      if (iterator) {
        let IpInfo = iterator.split(':')
        obj.push({
          ip: IpInfo[0] + ':' + IpInfo[1],
          auth: IpInfo[2] + ':' + IpInfo[3]
        })
      }
    }
    let randomList = getRandomElements(obj, obj.length)
    proxyipLst.value = randomList
    localStorage.setItem('proxyipLst', JSON.stringify(randomList))
  } else {
    proxyipLst.value = []
  }
}

function getRandomElements(arr, n) {
  let tmpArr = JSON.parse(JSON.stringify(arr))
  let result = new Array(n),
    len = tmpArr.length,
    taken = new Array(len)
  if (n > len) throw new RangeError('getRandomElements: input array is not long enough.')
  while (n--) {
    var x = Math.floor(Math.random() * len)
    result[n] = tmpArr[x in taken ? taken[x] : x]
    taken[x] = --len in taken ? taken[len] : len
  }
  return result
}

function cleanProxyIpList() {
  localStorage.removeItem('proxyipLst')
  proxyipLst.value = []
  ElMessage({
    type: 'success',
    message: '清除成功!'
  })
}

/**
 * 检查代理IP的有效性
 */
let loading2 = ref(false)
async function checkIpConnect() {
  if (!electron) {
    ElMessage({
      type: 'error',
      message: '当前环境不支持检测！'
    })
    return
  }
  if (proxyipLst.value.length == 0) {
    ElMessage({
      type: 'error',
      message: '请先获取代理IP！'
    })
    return
  }
  let tmp = proxyipLst.value.map((v) => {
    return v.ip
  })
  console.warn(tmp)
  electron.ipcRenderer.send('checkIp', JSON.stringify(tmp))
  loading2.value = true
}

//提取代理IP列表接口  type :0 ,短效IP 1~5分钟,     1为长效2~4个小时的IP   3为  半个小时~1个小时的IP
function getdps(type, num) {
  let url = ''
  let obj = {
    secret_id: '',
    signature: '',
    num,
    type
  }
  switch (type) {
    case 0:
      obj.secret_id = 'oeo9h93r1uvrrd25a5qj'
      obj.signature = 'cej52parcod7yx08s1h28g19d0foor8f'
      break
    case 1:
      obj.secret_id = 'oxussf5skcf5mny79xp4'
      obj.signature = 'i5xw1rhl0fpo00gj4p4tb4zedbef5ub6'
      break
    case 3:
      obj.secret_id = 'o87fgxhl5oab0nu3i9e1'
      obj.signature = 'o30hzzlg41jy7mc41p8rx3gl3lz2jviu'
      break
    default:
      break
  }
  url = `http://208.87.207.213/proxyIp2.txt`
  // url = `https://dps.kdlapi.com/api/getdps/?secret_id=o6txauks4c1twztpzytb&num=${obj.num}&signature=ugj49k7qhri33x72e95ou2kjslvv0yut&pt=1&sep=1`
  return url
}

/**
 *
 * @returns 获取任务列表
 *
 */
async function getDouYindTaskList(query = {}) {
  loading.value = true
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve(true)
    }, 100)
  })
  //获取当前登录用户信息
  let userInfo = localStorage.getItem('userinfo')
  if (!userInfo) {
    ElMessage({
      type: 'error',
      message: '登录用户信息为空!'
    })
    router.push({
      path: '/Login',
      query: {
        ...route.query
      }
    })
    return
  }
  let createdAt = dayjs().format('YYYY-MM-DD HH:mm:ss')
  let DouYionEquipment = `http://208.87.207.213:38390/DouYinTask/DouYindList?sgin=47CFD0A2EB7EA1DC043F1B91926890E9&status=0%2C1%2C-1&page=${pageIndex.value}&pageNo=${pageSize.value}`
  // const SendData = {}
  if (query['createdAt']) {
    DouYionEquipment += `&createdAt=${query['createdAt']}`
  } else {
    formInline.createdAt = createdAt
    DouYionEquipment += `&createdAt=${createdAt}`
  }
  if (formInline['task_name']) {
    DouYionEquipment += `&task_name=${query['task_name']}`
  }
  if (JSON.parse(userInfo).id) {
    DouYionEquipment += `&account_id=${JSON.parse(userInfo).id}`
  }
  const response_ = await fetch(DouYionEquipment, {
    method: 'GET',
    headers: {
      'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    body: undefined
  })
  let response = await response_.json()
  localStorage.setItem('DouYinTaskList', JSON.stringify(response.data))
  loading.value = false
  console.warn(response.data)
  total.value = response.data.count
  tableData.value = response.data.rows
}

/**
 *
 * @returns 更新任务列表
 *
 */
// 选择任务生成的wss连接地址
let generate_list = ref([])
async function DouYinTaskUpdate(rowdata, type) {
  if (!type) {
    if (TaskObjInfo.value.id) {
      ElMessage({
        type: 'error',
        message: '已选择开的的任务!'
      })
      return
    }
  }
  loading.value = true
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve(true)
    }, 100)
  })
  let DouYionEquipment = `http://208.87.207.213:38390/DouYinTask/DouYinTaskUpdate?sgin=47CFD0A2EB7EA1DC043F1B91926890E9`
  let SendData = {}
  if (type && type == 'add') {
    SendData['duration'] = parseInt(rowdata['duration']) + 1
    rowdata['duration'] = parseInt(rowdata['duration']) + 1
    // 任务结束时间加一小时
    if (endTime.value != '00:00:00') {
      endTime.value = dayjs(endTime.value).add(1, 'h').format('YYYY-MM-DD HH:mm:ss')
      SendData['end_time'] = endTime.value
      rowdata['end_time'] = endTime.value
    }
  }
  if (type && type == 'sub') {
    if (rowdata['duration'] == 1) {
      ElMessage({
        type: 'error',
        message: '时长必须大于1小时!'
      })
      loading.value = false
      return
    }
    SendData['duration'] = parseInt(rowdata['duration']) - 1
    rowdata['duration'] = parseInt(rowdata['duration']) - 1
    // 任务结束时间减去一小时
    if (endTime.value != '00:00:00') {
      endTime.value = dayjs(endTime.value).subtract(1, 'h').format('YYYY-MM-DD HH:mm:ss')
      SendData['end_time'] = endTime.value
      rowdata['end_time'] = endTime.value
    }
  }
  if (!rowdata['start_time']) {
    let time2 = dayjs().format('YYYY-MM-DD HH:mm:ss')
    SendData['start_time'] = time2
    rowdata['start_time'] = time2
  }
  if (!rowdata['end_time']) {
    let time = dayjs().add(rowdata.duration, 'h').format('YYYY-MM-DD HH:mm:ss')
    SendData['end_time'] = time
    rowdata['end_time'] = time
  } else {
    let time = dayjs(rowdata['start_time']).add(rowdata.duration, 'h').format('YYYY-MM-DD HH:mm:ss')
    SendData['end_time'] = time
    rowdata['end_time'] = time
  }
  const response_ = await fetch(DouYionEquipment, {
    method: 'POST',
    headers: {
      'content-type': 'application/json; charset=UTF-8'
    },
    body: JSON.stringify(
      Object.assign(
        {
          id: parseInt(rowdata.id),
          task_status: 2
        },
        SendData
      )
    )
  })
  loading.value = false
  let response = await response_.json()
  console.warn(response)
  if (response.code != 200) {
    ElMessage({
      type: 'error',
      message: '操作失败!' + response.msg
    })
    return
  }
  // 保存任务信息
  TaskObjInfo.value = JSON.parse(JSON.stringify(rowdata))
  document.title = '正在进行的任务(' + rowdata.task_name + ')'
  // // 批量生成wss连接地址
  // let wss_url_list = await getLiveRoomUrl()
  // console.warn('generate_list', wss_url_list)
  // generate_list.value = wss_url_list
  // await getDouYindTaskList()

  // sendTo(
  //   JSON.stringify({
  //     cmd: 'CreateTask',
  //     wss_list: wss_url_list
  //   })
  // )
}

/**
 *
 * @returns 删除任务列表
 *
 */
async function DouYinDelete(id) {
  try {
    ElMessage({
      type: 'error',
      message: '暂不支持删除!'
    })
    return
    loading.value = true
    await new Promise((resolve) => {
      setTimeout(() => {
        resolve(true)
      }, 100)
    })
    await ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    let DouYionEquipment = ``
    // const SendData = {}
    const response_ = await fetch(DouYionEquipment, {
      method: 'POST',
      headers: {
        'content-type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        id
      })
    })
    let response = await response_.json()
    loading.value = false
    console.warn(response)
    if (response.code != 200) {
      ElMessage({
        type: 'error',
        message: '操作失败!' + response.msg
      })
      return
    }
    ElMessage({
      type: 'success',
      message: '删除成功!'
    })
    await getDouYindTaskList()
  } catch (error) {
    loading.value = false
  }
}

let UpdateMessage = ref({ cmd: '' })
let version = ref(package_.version || '')
let percentage = ref(100)

onMounted(async () => {
  let DouYinTaskList = localStorage.getItem('DouYinTaskList')
  if (DouYinTaskList) {
    DouYinTaskList = JSON.parse(DouYinTaskList)
    total.value = DouYinTaskList.count
    tableData.value = DouYinTaskList.rows
  } else {
    await getDouYindTaskList()
  }

  if (electron) {
    electron.ipcRenderer.on('UpdateMessage', (event, data) => {
      console.warn(data)
      if (data.cmd && data.cmd == 'download-progress') {
        let percent = Math.trunc(data.message.percent) || 0
        percentage.value = percent
      }
      UpdateMessage.value = data
    })
    // 代理IP检查结果
    electron.ipcRenderer.on('checkIpResult', (event, data) => {
      console.warn(data)
      loading2.value = false
      if (!data) {
        ElNotification.error({
          title: '代理IP检查结果',
          message: data,
          offset: 100
        })
        return
      }
      ElNotification.success({
        title: '代理IP检查结果',
        message: data,
        offset: 100
      })
    })
  }
  // 获取代理ip
  getProxyIpList()
})

async function handleCurrentChange(number) {
  console.warn('handleCurrentChange', number)
  pageIndex.value = number
  await getDouYindTaskList()
}

/**
 *
 * @param {检查更新软件操作} cmd
 */
// eslint-disable-next-line no-unused-vars
async function checkForUpdate(cmd) {
  if (electron) {
    electron.ipcRenderer.send('checkForUpdate', true)
  }
}

// eslint-disable-next-line no-unused-vars
async function _blank_page(url) {
  if (electron) {
    electron.ipcRenderer.send('_blank_page', url)
  }
}

async function AddDouYindTask() {
  if (electron) {
    electron.ipcRenderer.send('_add_task_blank_page', 'http://208.87.207.213/dist/#/')
  }
}

/**
 *
 * 进入直播间wss地址
 *
 */
let startIndexa = ref(0)
let startIndexb = ref(0)
let startIndexc = ref(0)
async function getLiveRoomUrl(add_number = 0) {
  let HuoShanTokenList = []
  let DeviceList = []
  let number = TaskObjInfo.value.number
  let RoomUrlList = []
  // 已经开始的
  let default_ = generate_list.value.length
  console.warn('在线人气数量----->>>', TaskObjInfo.value.number)
  if (OnlineType.value == 2) {
    let HuoShanToken = localStorage.getItem('HuoShanTokenList')
    if (!HuoShanToken) {
      ElMessage({
        type: 'error',
        message: '没有可账号数据!'
      })
      return
    }
    let tmp = JSON.parse(HuoShanToken).rows
    HuoShanTokenList = tmp.slice(
      add_number ? startIndexb.value + default_ : startIndexb.value,
      add_number ? startIndexb.value + default_ + add_number : number + startIndexb.value
    )
  }
  if (OnlineType.value == 3) {
    let TokenList = localStorage.getItem('TokenList')
    if (!TokenList) {
      ElMessage({
        type: 'error',
        message: '没有可账号数据!'
      })
      return
    }
    let tmp2 = JSON.parse(TokenList)
    HuoShanTokenList = tmp2.slice(
      add_number ? startIndexc.value + default_ : startIndexc.value,
      add_number ? startIndexc.value + default_ + add_number : number + startIndexc.value
    )
  }
  let DouyinAccountList = localStorage.getItem('DouyinAccountList')
  if (!DouyinAccountList) {
    ElMessage({
      type: 'error',
      message: '没有可设备数据!'
    })
    return
  }
  let ipNumber = 0
  DeviceList = JSON.parse(DouyinAccountList).rows.slice(
    add_number ? startIndexa.value + default_ : startIndexa.value,
    add_number ? startIndexa.value + default_ + add_number : number + startIndexa.value
  )
  for (let index = 0; index < DeviceList.length; index++) {
    // let allParameter = localStorage.getItem('allParameter')
    // allParameter = JSON.parse(allParameter)
    // allParameter = allParameter.map((v) => {
    //   return v.extra.x_tt_token
    // })
    if (index % AccountIpNumber.value == 0) {
      ipNumber += 1
    }
    console.warn(proxyipLst.value[ipNumber])
    const element = DeviceList[index]
    let login_params = element.login_params
    // 设备对象信息
    let deviceInfo = {}
    // 设备整体数据解析
    let arr = login_params.split('ws_apps=')
    arr[0] = arr[0] + 'ws_apps='
    // 第一段数据截取 包含 mac_addr device_id
    let device_a = arr[0].split('#')
    // 第二段数据截取
    let device_b_arr = arr[1].split('#')
    // 包含手机信息  channel_id app_id mcc_mnc等 类型 对象数组字符串
    let device_c = device_b_arr[0]
    // 包含 device_token= dr_channel cookie
    let device_d = device_b_arr.slice(1, -1)

    // console.warn('device_a--->>', device_a)
    for (const iterator of device_a) {
      let sarr = iterator.split('=')
      deviceInfo[sarr[0]] = sarr[1]
    }
    // console.warn('device_b_arr--->>', device_b_arr)
    // console.warn('device_c--->>', JSON.parse(device_c))
    let jsonc = {}
    try {
      jsonc = JSON.parse(device_c)
    } catch (error) {
      jsonc = JSON.parse(device_c.replaceAll('\\', ''))
    }
    let device_c_extra = device_c ? jsonc[0].extra.split('&') : []
    let extra = {}
    for (const iterator of device_c_extra) {
      let sarr = iterator.split('=')
      extra[sarr[0]] = sarr[1]
    }
    deviceInfo = Object.assign(deviceInfo, device_c ? jsonc[0] : {})
    deviceInfo.extra = extra
    // console.warn('device_d--->>', device_d)
    for (const iterator of device_d) {
      let sarr = iterator.split('=')
      deviceInfo[sarr[0]] = sarr[1]
    }
    console.warn(deviceInfo)
    let newtime = new Date().getTime()
    let channel = deviceInfo['extra']['channel'] || ''
    let device_type = deviceInfo['extra']['device_type'] || ''
    let room_id = TaskObjInfo.value['room_id'] || ''
    let resolution = deviceInfo['extra']['resolution'] || ''
    let cdid = deviceInfo['extra']['cdid'] || ''
    let device_id = deviceInfo['extra']['device_id'] || ''
    let token = HuoShanTokenList[index] ? HuoShanTokenList[index].x_tt_token : ''
    let _rticket = newtime
    let iid = deviceInfo['extra']['iid'] || ''
    let openudid = deviceInfo['extra']['openudid'] || ''
    let sessionId = ''
    if (HuoShanTokenList[index] && HuoShanTokenList[index].x_tt_token) {
      sessionId = HuoShanTokenList[index].x_tt_token.slice(2, 34)
    }
    if (OnlineType.value == 1) {
      token = deviceInfo['token']
      sessionId = deviceInfo['token'].slice(2, 34)
    }
    let oaid = '9e6340801d21ffa3'
    let dpi = deviceInfo['extra']['dpi'] || ''
    let device_brand = deviceInfo['extra']['device_brand'] || ''
    let os_version = deviceInfo['extra']['os_version'] || '9'
    let version_name = deviceInfo['extra']['version_name'] || '20.7.0'
    let user_id = HuoShanTokenList[index] ? HuoShanTokenList[index].user_id_str : '0'
    let version_code = deviceInfo['extra']['version_code'] || '200700'
    let update_version_code = deviceInfo['extra']['update_version_code'] || '20709900'
    let manifest_version_code = deviceInfo['extra']['manifest_version_code'] || '200701'
    let host_abi = deviceInfo['extra']['host_abi'] || 'armeabi-v7a'
    let ts = parseInt(_rticket / 1000)
    let aid = deviceInfo['extra']['aid'] ? parseInt(deviceInfo['extra']['aid']) : 1128
    let access_key = api.md5('9e1bd35ec9db7b8d846de66ed140b1ad9' + device_id + 'f8a69f1719916z') //转换MD5
    let live_room_url = `wss://webcast100-ws-c.amemv.com/webcast/im/push/v2/?is_guest_mode=0&app_type=normal&room_tag=video&channel=${channel}&is_android_pad=0&device_type=${device_type}&language=zh&cpu_support64=true&live_cursor=0&rid=${room_id}&resolution=${resolution}&update_version_code=${update_version_code}&im-sdk-version=2&cdid=${cdid}&minor_status=0&need_persist_msg_count=12&parse_cnt=0&ac=wifi&package=com.ss.android.ugc.aweme&current_network_quality_info=%7B%7D&device_id=${device_id}&compress=gzip&recv_cnt=0&version_code=${version_code}&support_cache=1&im-x-tt-token=${token}&resp_content_type=protobuf&live_id=1&address_book_access=2&user_id=${user_id}&device_platform=android&aid=${aid}&cursor=0&room_id=${room_id}&last_rtt=0&manifest_version_code=${manifest_version_code}&_rticket=${_rticket}&webcast_gps_access=1&iid=${iid}&is_landscape=false&host_abi=${host_abi}&openudid=${openudid}&sid=${sessionId}&is_pad=false&appTheme=light&os_api=28&identity=audience&webcast_locale=zh_CN&dpi=${dpi}&oaid=${oaid}&carrier_region=CN&os=android&os_version=${os_version}&support_wrds=1&webcast_sdk_version=2650&app_name=aweme&version_name=${version_name}&device_brand=${device_brand}&need_personal_recommend=1&webcast_language=zh&ts=${ts}&which_ws=live_ws&version_code=${version_code}&iid=${iid}&platform=0&fpid=9&sdk_version=2&transport_mode=0&device_id=${device_id}&service_id_list=%5B%5D&private_protocol_enable=false&aid=${aid}&ttnet_ignore_offline=1&access_key=${access_key}&ne=1`
    RoomUrlList.push({
      webSocketUrl: live_room_url,
      proxy_ip: proxyipLst.value[ipNumber] ? proxyipLst.value[ipNumber].ip : '',
      auth: proxyipLst.value[ipNumber] ? proxyipLst.value[ipNumber].auth : ''
    })
  }
  return RoomUrlList
}

async function creatWebSocket() {
  if (!TaskObjInfo.value.id) {
    ElMessage({
      type: 'error',
      message: '没有选择开始的的任务!'
    })
    return
  }
  if (!ws_task) {
    ElMessage({
      type: 'error',
      message: '请连接Websocket服务!'
    })
    return
  }

  if (proxyipLst.value.length == 0) {
    ElMessage({
      type: 'error',
      message: '请更新代理IP数据!'
    })
    return
  }
  if (generate_list.value.length > 0) {
    ElMessage({
      type: 'error',
      message: '任务已经开始，请勿重复开始!'
    })
    return
  }
  // 批量生成wss连接地址
  let wss_url_list = await getLiveRoomUrl()
  console.warn('generate_list', wss_url_list)
  generate_list.value = wss_url_list
  await getDouYindTaskList()
  sendTo(
    JSON.stringify({
      cmd: 'CreateTask',
      wss_list: generate_list.value
    })
  )
  // 开始任务
  TaskReckonTime()
  return
  let ws
  for (let index = 0; index < generate_list.value.length; index++) {
    ws = new WebsocketBuild(generate_list.value[index].webSocketUrl)
    map_wss.value.push(ws)
    ws.onopen = () => {
      //操作数据后更新视图
      internalInstance.proxy.$forceUpdate()
    }
    ws.onclose = () => {
      //操作数据后更新视图
      internalInstance.proxy.$forceUpdate()
    }
  }
  window.map_wss = map_wss
  // 开始任务
  TaskReckonTime()
}

// setInterval(() => {
//   if (map_wss.value.length > 0) {
//     //操作数据后更新视图
//     internalInstance.proxy.$forceUpdate()
//     let num = 0
//     for (const iterator of map_wss.value) {
//       if (iterator.ws.readyState == 1) {
//         num++
//       }
//     }
//     wss_connect.value = num
//   } else {
//     wss_connect.value = 0
//     onlineUserForAnchor.value = '0'
//   }
// }, 2000)

/**
 *
 * @param {*} index
 * 结束一个连接
 */
async function destroyWebSocket(index) {
  if (map_wss.value[index]) {
    map_wss.value[index].destroyWebSocket()
    map_wss.value.splice(index, 1)
    internalInstance.proxy.$forceUpdate()
  }
}
let addNumber = ref(1)
// 添加人数
async function addWebSocket() {
  await getProxyIpList()
  console.warn('增加多少个', addNumber.value)
  // 批量生成wss连接地址
  let wss_url_list = await getLiveRoomUrl(addNumber.value)
  console.warn('增加多少个wss_url_list', wss_url_list)
  generate_list.value.push(...wss_url_list)
  sendTo(
    JSON.stringify({
      cmd: 'CreateTask',
      wss_list: wss_url_list
    })
  )
}

/**
 *
 * @param {*} index
 * 结束任务
 *
 */
async function EndTask(index) {
  for (const iterator of map_wss.value) {
    if (iterator.ws) {
      iterator.destroyWebSocket()
    }
  }
  map_wss.value = []
  generate_list.value = []
  // 移除任务缓存 结束定时器
  localStorage.removeItem(TaskObjInfo.value.id + '')
  TaskObjInfo.value = { number: 0 }
  showTime.value = '任务结束'
  document.title = '暂无开始的任务'
  if (clock.value) {
    clearInterval(clock.value)
    clock.value = null
  }
  if (ws_task) {
    ws_task.send(
      JSON.stringify({
        cmd: 'FinishTask',
        wss_list: []
      })
    )
  }
  ElMessage({
    type: 'success',
    message: '任务结束成功!'
  })
}

let CommonMessageData = protobufjson.CommonMessageData
let pushproto = protobufjson.pushproto
let RoomDataSyncMessage = protobufjson.RoomDataSyncMessage
let WebcastChatMessage = protobufjson.WebcastChatMessage
let WebcastRoomMessage = protobufjson.WebcastRoomMessage
let WebcastRoomIntroMessage = protobufjson.WebcastRoomIntroMessage
let WebcastGiftMessage = protobufjson.WebcastGiftMessage
let WebcastMemberMessage = protobufjson.WebcastMemberMessage
let WebcastRoomUserSeqMessage = protobufjson.WebcastRoomUserSeqMessage
let WebcastLikeMessage = protobufjson.WebcastLikeMessage
let root = protobuf.Root.fromJSON(pushproto)

class WebsocketBuild {
  // websocket对象
  ws = ''
  // websocket地址
  wsServer = ''
  // 断线重连次数
  limitConnect = 50
  // 累计断线重连次数
  timeConnect = 0
  // websocket binaryType
  binaryType = 'arraybuffer'
  // 定时器
  Interva = null
  // 直播间在线人数
  onlineUserForAnchor = 0
  // 房间聊天信息
  RoomMessage = []
  //url query 参数
  query = {}
  constructor(wsServer) {
    this.wsServer = wsServer
    this.webSocketStart(this.wsServer)
    // 解析url
    let parm_url = new URL(this.wsServer)
    for (const iterator of parm_url.searchParams) {
      this.query[iterator[0]] = iterator[1]
    }
  }
  destroyWebSocket = () => {
    if (this.ws) {
      this.limitConnect = 0
      this.ws.close()
    }
  }
  HeartBeat = () => {
    // 心跳 * 回应
    this.Interva = setInterval(() => {
      if (this.ws) {
        //CONNECTING：值为0，表示正在连接。
        //OPEN：值为1，表示连接成功，可以通信了。
        //CLOSING：值为2，表示连接正在关闭。
        //CLOSED：值为3，表示连接已经关闭，或者打开连接失败。
        if (this.ws.readyState === 1) {
          let Message = root.lookupType('pushproto.PushFrame')
          let message = Message.create({
            payloadType: 'hb'
          })
          let sendada = Message.encode(message).finish()
          this.ws.send(sendada)
          console.warn('发送心跳响应-----')
        }
      }
    }, 5000)
  }
  webSocketStart = () => {
    this.ws = new WebSocket(this.wsServer)
    this.ws.binaryType = 'arraybuffer'
    this.ws.onmessage = this.onmessage
    this.ws.onclose = this.onclose
    this.ws.onopen = this.onopen
  }
  onmessage = (msg) => {
    // console.log('wss服务器消息')
    let messageProto = root.lookup('pushproto.PushFrame')
    let data = msg.data
    let message = null
    try {
      message = messageProto.decode(new Uint8Array(data))
    } catch (error) {
      console.warn(error)
    }
    if (message.headersList.compress_type == 'gzip') {
      // console.warn('解压前----->>>>', message.payload)
      const output = pako.ungzip(message.payload)
      // console.warn('解压后----->>>>', output)
      let unGzipMessage = root.lookup('pushproto.Response')
      let gzipMessage = unGzipMessage.decode(output)
      // this.AnalysisData(gzipMessage.messagesList)
      if (gzipMessage.needAck) {
        let MessageLoad = root.lookupType('pushproto.PushFrame')
        let payload = (function (e) {
          const t = []
          for (const o of e) {
            const e = o.charCodeAt(0)
            e < 128
              ? t.push(e)
              : e < 2048
              ? (t.push(192 + (e >> 6)), t.push(128 + (63 & e)))
              : e < 65536 &&
                (t.push(224 + (e >> 12)), t.push(128 + ((e >> 6) & 63)), t.push(128 + (63 & e)))
          }
          return Uint8Array.from(t)
        })(gzipMessage.internalExt)
        // let message_res = MessageLoad.create({ payloadType: "ack", payload: payload, logid: message.logid });
        let headersList = []
        for (const key in message.headersList) {
          const element = message.headersList[key]
          headersList.push({
            [message.headersList[key]]: element
          })
        }
        let message_res = MessageLoad.create({
          payloadType: 'ack',
          payload: payload,
          logid: message.logid,
          headersList
        })
        let sendada = MessageLoad.encode(message_res).finish()
        this.ws.send(sendada)
        // console.warn('发送ACK响应-----')
      }
    }
  }
  // 数据解析
  AnalysisData = (data) => {
    try {
      let messagesList = data
      for (const iterator of messagesList) {
        // console.warn(iterator.method)
        let info = {}
        switch (iterator.method) {
          case 'WebcastRoomDataSyncMessage':
            let RoomDataSyncResult = protobuf.Root.fromJSON(RoomDataSyncMessage)
            let room_data_sync_message = RoomDataSyncResult.lookup('RoomDataSyncMessage')
            let RoomDataSyncData = room_data_sync_message.decode(iterator.payload)
            info = RoomDataSyncData.toJSON()
            // console.warn(info)
            if (info.user) {
              let msg = `${info.user.nickname} (${info.user.id})&sec_user_id=${info.user.secUid}`
              this.RoomMessage.push(msg)
            }
            break
          case 'WebcastChatMessage':
            let ChatMessageResult = protobuf.Root.fromJSON(WebcastChatMessage)
            let ChatMessage = ChatMessageResult.lookup('ChatMessages')
            let ChatMessageData = ChatMessage.decode(iterator.payload)
            // console.warn(ChatMessageData.toJSON())
            info = ChatMessageData.toJSON()
            let msg = `${info.user.nickname} (${info.user.id}):${info.content}&sec_user_id=${info.user.secUid}`
            this.RoomMessage.push(msg)
            break
          case 'WebcastRoomMessage':
            let WebcastRoomResult = protobuf.Root.fromJSON(WebcastRoomMessage)
            let webcast_roomMessage = WebcastRoomResult.lookup('WebcastRoomMessage')
            let MessageData = webcast_roomMessage.decode(iterator.payload)
            // console.warn(MessageData.toJSON())
            info = MessageData.toJSON()
            let msg2 = `${info.user.nickname} (${info.user.id}):进入直播间&sec_user_id=${info.user.secUid}`
            this.RoomMessage.push(msg2)
            break
          case 'WebcastRoomIntroMessage':
            let RoomIntroResult = protobuf.Root.fromJSON(WebcastRoomIntroMessage)
            let RoomIntroMessageData = RoomIntroResult.lookup('RoomIntro.RoomIntroMessage')
            let RoomIntroData = RoomIntroMessageData.decode(iterator.payload)
            // console.warn(RoomIntroData.toJSON())
            info = RoomIntroData.toJSON()
            let msg3 = ` ${info.user.nickname} (${info.user.id}):&sec_user_id=${info.user.secUid}`
            this.RoomMessage.push(msg3)
            break
          case 'WebcastGiftMessage':
            let GiftMessageResult = protobuf.Root.fromJSON(WebcastGiftMessage)
            let GiftMessageMessageData = GiftMessageResult.lookup('dy.GiftMessage')
            let GiftMessageData = GiftMessageMessageData.decode(iterator.payload)
            // console.warn(GiftMessageData.toJSON())
            info = GiftMessageData.toJSON()
            let msg4 = `${info.user.nickname} (${info.user.id}):送礼物&sec_user_id=${info.user.secUid}`
            this.RoomMessage.push(msg4)
            break
          case 'WebcastMemberMessage':
            let MemberMessageResult = protobuf.Root.fromJSON(WebcastMemberMessage)
            let MemberMessageData = MemberMessageResult.lookup('MemberMessage')
            let MemberData = MemberMessageData.decode(iterator.payload)
            // console.warn(MemberData.toJSON())
            info = MemberData.toJSON()
            let msg5 = `${info.user.nickname} (${info.user.id}):来了&sec_user_id=${info.user.secUid}`
            this.RoomMessage.push(msg5)
            break
          case 'WebcastLikeMessage':
            let LikeMessageResult = protobuf.Root.fromJSON(WebcastLikeMessage)
            let LikeMessageData = LikeMessageResult.lookup('LikeMessage')
            let LikeData = LikeMessageData.decode(iterator.payload)
            // console.warn(LikeData.toJSON())
            info = LikeData.toJSON()
            let msg6 = `${info.user.nickname} (${info.user.id}):点赞&sec_user_id=${info.user.secUid}`
            this.RoomMessage.push(msg6)
            break
          case 'WebcastRoomUserSeqMessage':
            let RoomUserSeqResult = protobuf.Root.fromJSON(WebcastRoomUserSeqMessage)
            let SeqMessageData = RoomUserSeqResult.lookup('RoomUserSeqMessage')
            let SeqData = SeqMessageData.decode(iterator.payload)
            // console.warn(SeqData.toJSON())
            info = SeqData.toJSON()
            // 当前直播间人数
            if (info.onlineUserForAnchor) {
              this.onlineUserForAnchor = info.onlineUserForAnchor
              onlineUserForAnchor.value = info.onlineUserForAnchor
              console.warn('当前直播间人数---->>>', this.onlineUserForAnchor)
            }
            break
          default:
            break
        }
      }
    } catch (error) {}
  }
  onclose = () => {
    console.log('wss服务器已经断开')
    this.reconnect(this.wsServer)
  }
  onopen = () => {
    console.log('已连接wss服务器')
    this.HeartBeat()
  }
  reconnect = () => {
    // lockReconnect加锁，防止onclose、onerror两次重连
    if (this.limitConnect > 0) {
      this.limitConnect--
      this.timeConnect++
      // console.log('第' + this.timeConnect + '次重连')
      // 进行重连
      setTimeout(() => {
        this.webSocketStart(this.wsServer)
      }, 2000)
    } else {
      // console.log('wss连接已超时')
    }
  }
}

// 表单提交
const onSubmit = async () => {
  console.log('submit!')
  await getDouYindTaskList(formInline)
}
</script>

<template>
  <div class="container no-drag">
    <div class="search">
      <el-form :inline="true" :model="formInline" ref="queryForm">
        <el-form-item label="任务标题：">
          <el-input v-model="formInline.task_name" placeholder="请输入任务标题" />
        </el-form-item>
        <el-form-item label="任务创建时间：">
          <!-- <el-date-picker v-model="formInline.createdAt" type="date" placeholder="请选择时间" size="default" /> -->
          <el-input
            v-model="formInline.createdAt"
            :value="formInline.createdAt"
            type="datetime-local"
            placeholder="请选择时间"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      empty-text="暂无数据"
      border
      row-key="id"
      size="large"
      stripe
      style="width: 100%"
      height="200"
      highlight-current-row
      :header-cell-style="{ background: '#F9F9F9', color: '#606266' }"
    >
      <el-table-column
        v-for="(item, index) in columns"
        :key="index"
        :align="item.align"
        :show-overflow-tooltip="true"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        :fixed="item.fixed"
      >
        <template #default="scope">
          <div v-if="item.prop == 'live_url'">
            <el-link type="primary" @click="_blank_page(scope.row[item.prop])">{{
              scope.row[item.prop]
            }}</el-link>
          </div>
          <div v-else-if="item.prop == 'id'">
            {{ scope.$index + 1 }}
          </div>
          <div v-else-if="item.prop == 'task_status'">
            <el-link type="primary" v-if="scope.row[item.prop] == 1">待开始</el-link>
            <el-link type="success" v-else>进行中</el-link>
          </div>
          <div v-else-if="item.prop == 'operation'">
            <el-button size="small" type="primary" @click="DouYinTaskUpdate(scope.row)"
              >选择开始任务</el-button
            >
            <el-button size="small" type="danger" @click="DouYinTaskUpdate(scope.row, 'sub')"
              >减1小时</el-button
            >
            <el-button size="small" type="warning" @click="DouYinTaskUpdate(scope.row, 'add')"
              >加1小时</el-button
            >
          </div>
          <div v-else>{{ scope.row[item.prop] }}</div>
        </template>
      </el-table-column>
    </el-table>
    <el-button
      style="margin-top: 10px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)"
      class="no-drag"
      type="danger"
      @click="checkForUpdate"
      >APP检查更新{{ '(当前版本号:' + version + ')' }}</el-button
    >
    <div class="progress" v-if="UpdateMessage.cmd == 'download-progress'">
      <el-progress type="circle" :percentage="percentage" />
    </div>
    <el-button
      style="margin-top: 10px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)"
      type="primary"
      size="small"
      @click="getDouYindTaskList"
      >更新任务列表</el-button
    >
    <el-button
      style="margin-top: 10px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)"
      type="primary"
      size="small"
      @click="AddDouYindTask"
      >添加、新建任务</el-button
    >
    <el-row style="margin-top: 10px">
      <label>更新IP数量：</label>
      <el-input-number v-model="ProxyIpNumber"></el-input-number>
      <el-col :span="24">
        <label>更新IP类型：</label>
        <el-radio-group v-model="ProxyIpLType">
          <el-radio :label="0">短效IP 1~5分钟</el-radio>
          <el-radio :label="1">长效2~4个小时</el-radio>
          <el-radio :label="3">半个小时~1个小时</el-radio>
        </el-radio-group>
      </el-col>
    </el-row>
    <el-button
      style="margin-top: 10px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)"
      type="primary"
      size="small"
      @click="cleanProxyIpList"
      >清除代理IP池</el-button
    >
    <el-button
      style="margin-top: 10px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)"
      type="primary"
      size="small"
      @click="getProxyIpList"
      >更新代理IP池</el-button
    >
    <el-button
      style="margin-top: 10px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)"
      type="primary"
      size="small"
      @click="checkIpConnect"
      :loading-icon="Eleme"
      :loading="loading2"
      >检查代理IP有效性</el-button
    >
    <div class="total_tatistics">
      <span>代理IP是否验证账号密码： </span>
      <el-input v-model="ProxyAuth" style="width: 120px"></el-input>
    </div>
    <div class="total_tatistics">
      <span>每个{{ AccountIpNumber }}个账户号使用1个IP： </span>
      <el-input-number v-model="AccountIpNumber" style="width: 100px"></el-input-number>
    </div>
    <div class="total_tatistics">
      <span>设备账号选择区间： </span>
      <span>设备登录--startIndexa-</span
      ><el-input-number v-model="startIndexa" style="width: 120px"></el-input-number>
      <span>上榜用户登录--startIndexb-</span
      ><el-input-number v-model="startIndexb" style="width: 120px"></el-input-number>
      <span>不上榜用户登录-startIndexc-</span
      ><el-input-number v-model="startIndexc" style="width: 120px"></el-input-number>
    </div>
    <div class="total_tatistics">
      <span
        >WebSocket任务服务: <el-input v-model="WebSocketStr" style="width: 250px"></el-input>
      </span>
      <el-button type="primary" style="margin-left: 5px" @click="ws_taskOpen">连接</el-button>
      <el-button type="danger" @click="ws_taskClose">断开</el-button>
    </div>
    <!-- 合计统计显示 -->
    <div class="total_tatistics">
      <span>总任务数：{{ total || '0' }} </span>
    </div>
    <div class="pagination">
      <el-pagination
        :current-page="pageIndex"
        layout=" prev, pager, next"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="total"
        background
        prev-text="上一页"
        next-text="下一页"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 直播任务信息 -->
    <div class="live">
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple-dark">
            <h3>直播任务信息:</h3>
            {{ TaskObjInfo.task_name }}
          </div>
          <div
            style="text-align: center; padding: 10px; font-size: 30px; font-weight: 600"
            v-if="TaskObjInfo.task_name"
          >
            {{ '正在进行的任务' + TaskObjInfo.task_name }}
          </div>
          <div style="text-align: center; padding: 10px; color: red; font-size: 20px">
            直播任务计时:{{ showTime }}（{{ endTime }}）
          </div>
          <div>
            任务需要在线人气数量：<el-input-number v-model="TaskObjInfo.number"></el-input-number>
            <span style="margin-left: 21px; color: red"
              >输入添加的数量：<el-input-number v-model="addNumber"></el-input-number
            ></span>
            <el-button style="margin-left: 10px" type="primary" @click="addWebSocket"
              >继续增加</el-button
            >
          </div>
          <div>当前代理IP池：{{ proxyipLst.length }}</div>
          <div>连接数：{{ generate_list.length || 0 }}</div>
          <!-- <div>当前直播间人数：{{ onlineUserForAnchor || 0 }}</div> -->
          <!-- <div>查看直播间消息：<el-button type="primary" >查看</el-button></div> -->
          <div>有效连接数：{{ wss_connect || 0 }}</div>
        </el-col>
        <el-col :span="24">
          <label>类型：</label>
          <el-radio-group v-model="OnlineType">
            <el-radio :label="1">1</el-radio>
            <el-radio :label="2">2</el-radio>
            <el-radio :label="3">3</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
      <span></span>
      <el-button type="primary" @click="creatWebSocket">开始任务</el-button>
      <el-button type="danger" @click="EndTask">结束任务</el-button>
      <div class="tablebox" style="height: 400px; overflow: auto">
        <table border="1" cellspacing="0" cellpadding="0" style="width: 100%; margin-top: 10px">
          <thead>
            <tr>
              <th>序号</th>
              <th>用户Id</th>
              <th>用户名称</th>
              <th>房间号</th>
              <th>设备号</th>

              <th>wss连接状态</th>
              <th>wss连接地址</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody v-if="map_wss.length > 0">
            <tr v-for="(item, index) in map_wss" :key="index" style="text-align: center">
              <td>{{ index + 1 }}</td>
              <td>{{ item.query['user_id'] }}</td>
              <td></td>
              <td>{{ item.query['room_id'] }}</td>
              <td>{{ item.query['device_id'] }}</td>
              <td>{{ ['正在连接', '连接成功', '连接关闭', '连接失败'][item.ws.readyState] }}</td>
              <td>
                <div>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="item.wsServer"
                    placement="bottom-end"
                  >
                    <el-button>查看</el-button>
                  </el-tooltip>
                </div>
              </td>
              <td>
                <div>
                  <el-button type="danger" size="small" @click="destroyWebSocket(index)">{{
                    item.readyState != 1 ? '移除连接' : '销毁连接'
                  }}</el-button>
                </div>
              </td>
            </tr>
          </tbody>
          <tbody style="display: flex; justify-content: center; align-items: center" v-else>
            暂无数据
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<style lang="less">
.tablebox {
  table tbody {
    display: block;
    height: 200px;
    overflow-y: scroll;
  }

  table thead,
  tbody tr {
    display: table;
    width: 100%;
    table-layout: fixed;
  }

  .left .el-tooltip__popper,
  .right .el-tooltip__popper {
    padding: 8px 10px;
  }
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.total_tatistics {
  padding: 12px;
  font-family: auto;
  font-size: 15px;
  font-weight: bold;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 19px;
}
</style>
